import React, { useState, useContext, useRef, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Modal,
  TextInput,
  TouchableWithoutFeedback,
  ActivityIndicator,
  Alert,
} from "react-native";
import OpinionsContext from "../../context/questionnaire/OpinionsContext";
import userQuesContext from "../../context/questionnaire/UserQuesContext";
import Dropdown from "../../components/dropdown";
import LoadingBar from "../../components/InterView/LoadingBar";
import OpinionsLocations from "../../components/opinionsLocation";
import Toast from "react-native-root-toast";
import { store } from "../../store/index";
import { Feather } from "@expo/vector-icons";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { Entypo } from "@expo/vector-icons";
import { MaterialIcons } from "@expo/vector-icons";
import { AntDesign } from "@expo/vector-icons";

const Loading = () => {
  return (
    <View style={styles.alterView}>
      <ActivityIndicator animating={true} size={"large"} color="#bbb" />
      <Text style={{ color: "#aaa", marginTop: 10 }}>Loading...</Text>
    </View>
  );
};

const Error = () => {
  return (
    <View style={styles.alterView}>
      <Text style={{ color: "#aaa", marginTop: 10 }}>请求超时...</Text>
    </View>
  );
};

const Opinions = ({ navigation }) => {
  const {
    opinionsLoading,
    GroupQuesData,
    addReply,
    examineQues,
    exportExcel,
    getGroupQues,
    exportAllExcel,
    getExcelByGroup,
    villageArr,
    pageLen,
  } = useContext(OpinionsContext);
  const { updateQues } = useContext(userQuesContext);

  const [pageInputVisible, setPageInputVisible] = useState(false);
  const [page, setPage] = useState(1);

  useEffect(() => {
    getGroupQues(1);
    setPage(1);
  }, []);

  // const getExcelByGroup = async () => {
  //   const user = store.getState().authR.user;
  //   let group;
  //   if (user.role == "admin") {
  //     group = user.group;
  //     try {
  //       let data = await queryApi.get("excel/group/" + group);
  //       // await Clipboard.setString(data.data.data.excelurl);
  //       console.log("下载成功---", data.data.data);
  //       // Alert.alert("已将下载地址" + data.data.data.excelurl + "复制到剪切板");
  //     } catch (error) {
  //       Alert.alert("下载失败---", error);
  //     }
  //   } else {
  //     group = "-1";
  //     Alert.alert("审核员不开放此功能");
  //   }
  // };

  const user = store.getState().authR.user;
  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <View style={{ flexDirection: "row" }}>
          {user.role == "admin" ? (
            <View style={{ flexDirection: "row" }}>
              <TouchableOpacity
                style={{ marginRight: 20 }}
                onPress={async () => {
                  console.log("下载");
                  getExcelByGroup();
                }}
              >
                <Entypo name="link" size={20} color="#fff" />
              </TouchableOpacity>
              <TouchableOpacity
                style={{ marginRight: 20 }}
                onPress={async () => {
                  exportAllExcel();
                }}
              >
                <MaterialCommunityIcons
                  name="upload-multiple"
                  size={20}
                  color="#fff"
                />
              </TouchableOpacity>
            </View>
          ) : null}

          <TouchableOpacity
            onPress={() => {
              console.log("刷新");
              // console.log("页码---", page);
              getGroupQues(1);
              setPage(1);
            }}
          >
            <Feather name="refresh-cw" size={20} color="#fff" />
          </TouchableOpacity>
        </View>
      ),
    });
  }, [navigation]);

  // 发消息Modal
  const [isVisible, setIsVisible] = useState(false);

  // 问卷序号
  const [quesIndex, setQuesIndex] = useState(-1);
  // 回复的对象
  const [replyRole, setReplyRole] = useState("");
  // 回复内容
  const [replyText, setReplyText] = useState("");
  // 调查户类型
  const [target, setTarget] = useState(7);
  // 选择的村代码
  const [villageValue, setVillageValue] = useState(0);

  const [isExporting, setIsExporting] = useState(false);
  const [isReplying, setIsReplying] = useState(false);

  // 级别
  const [level, setLevel] = useState(0);
  // 市
  const [cityCode, setCityCode] = useState("");
  // 县
  const [areaCode, setAreaCode] = useState("");

  // 调查户类型数组
  const typeOptions = [
    "脱贫稳定户",
    "脱贫不稳定户",
    "突发困难严重户1",
    "突发困难严重户2",
    "边缘易致贫户",
    "其他户（长）",
    "其他户（短）",
    "全部",
  ];
  const stateArr = ["待审核", "已通过", "已驳回", "全部"];

  const [isAllSelect, setIsAllSelect] = useState(false);
  const [quesSelectedArr, setQuesSelected] = useState([]);
  const [stateSelected, setStateSelected] = useState(0);
  useEffect(() => {
    let t_arr = [];
    for (let i = 0; i < GroupQuesData.length; i++) {
      t_arr.push(false);
    }
    setQuesSelected([...t_arr]);
    // console.log("选择---", quesSelectedArr);
  }, [GroupQuesData]);

  // 审核问卷
  const examine = async (index, state, callback) => {
    await examineQues(index, state, callback);
  };

  // 导出Excel
  const handleExportExcel = async () => {
    if (quesSelectedArr.lenghth == 0) {
      Toast.show("暂无可以导出的问卷", {
        duration: 700,
        position: Toast.positions.CENTER,
        animation: true,
      });
    } else {
      let flag = quesSelectedArr[0];
      for (let i = 0; i < quesSelectedArr.length; i++) {
        flag = flag || quesSelectedArr[i];
      }
      if (flag) {
        setIsExporting(true);
        await exportExcel(quesSelectedArr, "问卷");
        setIsExporting(false);
        // 清除选择
        setQuesSelected((preArr) => {
          return preArr.map((item, index) => {
            return false;
          });
        });
      } else {
        Toast.show("请先选择需要导出的问卷", {
          duration: 700,
          position: Toast.positions.CENTER,
          animation: true,
        });
      }
    }
  };

  const selectLoacation = (key, code) => {
    setLevel(key);
    if (key == 1) {
      setCityCode(code);
      setAreaCode("");
    } else if (key == 2) {
      setAreaCode(code);
    }
    setQuesSelected((preArr) => {
      return preArr.map((value, index) => {
        return false;
      });
    });
    setIsAllSelect(false);
  };

  return (
    <View style={styles.container}>
      <LoadingBar visible={opinionsLoading == "ing"} />

      <View style={{ height: "100%" }}>
        {/* 调查户类型选择 */}
        <View style={styles.dropdownView}>
          <Text style={{ marginTop: 8.5 }}>调查户类型：</Text>
          <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: target,
              initOptions: typeOptions,
            }}
            initialStyles={{
              valueWith: 140,
              optionsWidth: 150,
              valueFontSize: 14,
              optionsMarginTop: 10,
              optionsBackGroundColor: "#f1f1f1",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(item, value) => {
              setTarget(value);
              setQuesSelected((preArr) => {
                return preArr.map((value, index) => {
                  return false;
                });
              });
              setIsAllSelect(false);
            }}
          ></Dropdown>
        </View>
        <View style={styles.dropdownView}>
          <Text style={{ marginTop: 8.5 }}>问卷状态：</Text>
          <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: stateSelected,
              initOptions: stateArr,
            }}
            initialStyles={{
              valueWith: 140,
              optionsWidth: 150,
              valueFontSize: 14,
              optionsMarginTop: 50,
              optionsBackGroundColor: "#f1f1f1",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(item, value) => {
              setStateSelected(value);
              setQuesSelected((preArr) => {
                return preArr.map((value, index) => {
                  return false;
                });
              });
              setIsAllSelect(false);
            }}
          ></Dropdown>
        </View>
        <View style={styles.dropdownView}>
          {/* <Text style={{ marginTop: 8.5 }}>村代码：</Text>
            <Dropdown
              ifFirst={1}
              initialValues={{
                initKey: villageValue,
                initOptions: villageArr,
              }}
              initialStyles={{
                valueWith: 140,
                optionsWidth: 150,
                valueFontSize: 14,
                optionsMarginTop: 90,
                optionsBackGroundColor: "#f1f1f1",
                optionsBorderColor: "#ccc",
              }}
              onSelect={(item, value) => {
                setVillageValue(value);
              }}
            ></Dropdown> */}
          <TouchableOpacity
            onPress={() => {
              // setIsToday(!isToday);
              setLevel(0);
              setQuesSelected((preArr) => {
                return preArr.map((value, index) => {
                  return false;
                });
              });
              setIsAllSelect(false);
            }}
          >
            <View
              style={[
                styles.tag,
                { backgroundColor: level == 0 ? "#41C3EE" : "#ffffff" },
              ]}
            >
              <Text style={{ fontSize: 12 }}>全省</Text>
            </View>
          </TouchableOpacity>
          <OpinionsLocations
            selectLocation={selectLoacation}
          ></OpinionsLocations>
        </View>
        <View style={{ flex: 13 }}>
          <ScrollView>
            {GroupQuesData.map((ques, index) => {
              // console.log();
              // console.log(ques.title, "---", ques.user);
              let o_time = new Date(ques.time);
              o_time =
                o_time.getFullYear() +
                "年" +
                (o_time.getMonth() + 1) +
                "月" +
                o_time.getDate() +
                "日 " +
                o_time.getHours() +
                ":" +
                o_time.getMinutes();
              // 展示选择类型的问卷或全部，
              if (
                (target == ques.target || target == 7) &&
                // (villageArr[villageValue] ==
                //   ques.body[0].contents[1].answer.trim() ||
                //   villageArr[villageValue] == "全部") &&
                // ques.state != 0 &&
                (level == 0 ||
                  (level == 1 &&
                    ques.body[0].contents[0].title[0].answer[0] == cityCode) ||
                  (level == 2 &&
                    ques.body[0].contents[0].title[0].answer[1] == areaCode)) &&
                (stateSelected == 3 || ques.state == stateSelected + 1)
              ) {
                return (
                  <View
                    key={index}
                    style={{ borderTopWidth: 10, borderTopColor: "#eee" }}
                  >
                    <View style={styles.headView}>
                      <TouchableOpacity
                        style={{
                          paddingLeft: 3,
                          paddingRight: 10,
                          paddingTop: 1,
                        }}
                        onPress={() => {
                          setQuesSelected((preArr) => {
                            return preArr.map((value, v_index) => {
                              return index == v_index ? !value : value;
                            });
                          });
                        }}
                      >
                        <View
                          style={
                            quesSelectedArr[index]
                              ? styles.selectedView
                              : styles.selectView
                          }
                        ></View>
                      </TouchableOpacity>
                      <TouchableOpacity
                        onPress={() => {
                          updateQues(ques);
                          navigation.navigate("填写问卷", {
                            quesIndex: index,
                            isEdit: false,
                            isAdd: false,
                            btnType: 2,
                            examine,
                          });
                        }}
                      >
                        <View
                          style={{
                            flexDirection: "row",
                            justifyContent: "space-between",
                          }}
                        >
                          <Text
                            style={{
                              fontSize: 17,
                              fontWeight: "bold",
                              color: "#000",
                              // "A9D67C" "F47C68" "5ACCDA" "#68a6ff"
                            }}
                          >
                            {ques.title}
                          </Text>
                          {ques.state == 1 ? (
                            <View style={styles.stateView0}>
                              <Text style={{ color: "#777", fontSize: 13 }}>
                                待审核
                              </Text>
                            </View>
                          ) : null}
                          {ques.state == 2 ? (
                            <View style={styles.stateView1}>
                              <Text style={{ color: "#777", fontSize: 13 }}>
                                已通过
                              </Text>
                            </View>
                          ) : null}
                          {ques.state == 3 ? (
                            <View style={styles.stateView2}>
                              <Text style={{ color: "#777", fontSize: 13 }}>
                                已驳回
                              </Text>
                            </View>
                          ) : null}
                        </View>
                        <View style={{ flexDirection: "row", marginTop: 5 }}>
                          <View style={{ flexDirection: "row", width: 80 }}>
                            <Feather
                              name="user-check"
                              size={12}
                              color="#aaa"
                              style={{ marginTop: 7, marginRight: 4 }}
                            />
                            <Text
                              style={{
                                color: "#777",
                                marginTop: 4,
                                fontSize: 13,
                              }}
                            >
                              {ques.user.name}
                            </Text>
                          </View>
                          <View style={{ flexDirection: "row", width: 70 }}>
                            <MaterialIcons
                              name="group"
                              size={14}
                              color="#aaa"
                              style={{ marginTop: 6.4, marginRight: 4 }}
                            />
                            <Text
                              style={{
                                color: "#777",
                                marginTop: 4,
                                fontSize: 13,
                              }}
                            >
                              {ques.group}
                            </Text>
                          </View>
                          <View style={{ flexDirection: "row" }}>
                            <MaterialIcons
                              name="access-time"
                              size={12}
                              color="#aaa"
                              style={{ marginTop: 7, marginRight: 4 }}
                            />
                            <Text
                              style={{
                                color: "#777",
                                marginTop: 4,
                                fontSize: 13,
                              }}
                            >
                              {o_time}
                            </Text>
                          </View>
                        </View>
                      </TouchableOpacity>
                    </View>
                    <View
                      style={{
                        paddingLeft: 10,
                        paddingLeft: 10,
                        marginLeft: 5,
                        marginRight: 5,
                        // backgroundColor: "#eee",
                      }}
                    >
                      {/* {ques.opinions.opinions.map((opinion, opinionIndex) => {
                          return (
                            <TouchableOpacity
                              key={opinionIndex}
                              onPress={() => {
                                setQuesIndex(index);
                                setReplyRole(opinion.publisher);
                                setIsVisible(true);
                              }}
                            >
                              <View
                                style={{
                                  flexDirection: "row",
                                  marginBottom: 4,
                                  // backgroundColor: "#eee",
                                }}
                              >
                                <Text style={{ fontWeight: "bold" }}>
                                  {opinion.publisher}
                                </Text>
                                {opinion.recipient != "" ? (
                                  <View style={{ flexDirection: "row" }}>
                                    <Text style={{ color: "#aaa" }}>
                                      {" 回复 "}
                                    </Text>
                                    <Text style={{ fontWeight: "bold" }}>
                                      {opinion.recipient}
                                    </Text>
                                  </View>
                                ) : null}

                                <Text>：</Text>
                                <Text
                                  style={{
                                    // backgroundColor: "#eee",
                                    width: "84%",
                                    flexWrap: "wrap",
                                  }}
                                >
                                  {opinion.content}
                                </Text>
                              </View>
                            </TouchableOpacity>
                          );
                        })} */}
                    </View>
                    <View>
                      <TouchableOpacity
                        style={{
                          margin: 7,
                          marginBottom: 10,
                          marginRight: 20,
                          alignItems: "center",
                        }}
                        onPress={() => {
                          setQuesIndex(index);
                          setReplyRole("");
                          setIsVisible(true);
                        }}
                      >
                        <Text style={{ color: "#41C3EE" }}>发表意见</Text>
                      </TouchableOpacity>
                    </View>
                  </View>
                );
              }
            })}
          </ScrollView>
        </View>

        <View
          style={{
            flex: 1.3,
            alignItems: "center",
            flexDirection: "row",
            justifyContent: "space-between",
          }}
        >
          <View
            style={{ flexDirection: "row", marginBottom: 8, marginLeft: 5 }}
          >
            <TouchableOpacity
              onPress={() => {
                if (page > 1) {
                  getGroupQues(page - 1);
                  setPage(page - 1);
                } else {
                  Alert.alert("当前为第一页");
                }
              }}
            >
              <AntDesign name="left" size={24} color="black" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                setPageInputVisible(true);
              }}
            >
              <Text style={{ marginTop: 2, marginLeft: 2, marginRight: 2 }}>
                {page + " / " + Math.ceil(pageLen / 30)}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                if (page < Math.ceil(pageLen / 30)) {
                  getGroupQues(page + 1);
                  setPage(page + 1);
                } else {
                  Alert.alert("当前为最后一页");
                }
              }}
            >
              <AntDesign name="right" size={24} color="black" />
            </TouchableOpacity>
          </View>
          <TouchableOpacity
            style={styles.backBtn}
            onPress={async () => {
              setQuesSelected((preArr) => {
                return preArr.map((value, index) => {
                  if (
                    (target == GroupQuesData[index].target || target == 7) &&
                    (level == 0 ||
                      (level == 1 &&
                        GroupQuesData[index].body[0].contents[0].title[0]
                          .answer[0] == cityCode) ||
                      (level == 2 &&
                        GroupQuesData[index].body[0].contents[0].title[0]
                          .answer[1] == areaCode)) &&
                    ((stateSelected == 3 && GroupQuesData[index].state != 0) ||
                      GroupQuesData[index].state == stateSelected + 1)
                  ) {
                    if (isAllSelect) {
                      return false;
                    } else {
                      return true;
                    }
                  }
                });
              });
              setIsAllSelect(!isAllSelect);
            }}
          >
            <Text style={{ color: "#41C3EE" }}>
              {isAllSelect ? "全不选" : "全选"}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => {
              handleExportExcel();
            }}
          >
            <Text style={{ color: "#fff" }}>导出Excel</Text>
          </TouchableOpacity>
        </View>
      </View>
      {opinionsLoading == "error" ? <Error></Error> : null}

      {/* 输入评论 */}
      <Modal animationType="fade" transparent={true} visible={isVisible}>
        <View style={styles.ModalBackground}></View>
        <TouchableWithoutFeedback
          onPress={() => {
            setIsVisible(false);
          }}
        >
          <View style={styles.ModalTop}></View>
        </TouchableWithoutFeedback>
        <View
          style={{
            // flex: 1,
            backgroundColor: "#fff",
            flexDirection: "row",
            padding: 10,
            height: 60,
          }}
        >
          <TextInput
            style={styles.inputBox}
            multiline={true}
            // maxLength={500}
            value={replyText}
            placeholder={replyRole == "" ? "发表你的意见" : "回复" + replyRole}
            // editable={isEdit}
            onChangeText={(text) => {
              setReplyText(text);
            }}
          ></TextInput>
          <TouchableOpacity
            style={styles.replyBtn}
            disabled={replyText == "" ? true : false}
            onPress={async () => {
              setIsReplying(true);
              let replyDetail = {
                publisher: "",
                recipient: replyRole,
                content: replyText,
              };
              await addReply(quesIndex, replyDetail);
              setReplyText("");
              setIsVisible(false);
              setIsReplying(false);
            }}
          >
            <Text>发送</Text>
          </TouchableOpacity>
        </View>
      </Modal>
      {/* 输入页码 */}
      <Modal animationType="fade" transparent={true} visible={pageInputVisible}>
        <View style={styles.ModalBackground}></View>
        <TouchableWithoutFeedback
          onPress={() => {
            setPageInputVisible(false);
          }}
        >
          <View style={styles.ModalTop}></View>
        </TouchableWithoutFeedback>
        <View
          style={{
            // flex: 1,
            backgroundColor: "#fff",
            flexDirection: "row",
            padding: 10,
            height: 60,
          }}
        >
          <TextInput
            style={styles.inputBox}
            multiline={true}
            // maxLength={500}
            // value={page.toString()}
            placeholder={"输入页码"}
            // editable={isEdit}
            onChangeText={(text) => {
              setPage(Number(text));
            }}
          ></TextInput>
          <TouchableOpacity
            style={styles.replyBtn}
            disabled={page < 1 || page > Math.ceil(pageLen / 30) ? true : false}
            onPress={async () => {
              getGroupQues(page);
              setPageInputVisible(false);
            }}
          >
            <Text>查找</Text>
          </TouchableOpacity>
        </View>
      </Modal>
      <Modal animationType="fade" transparent={true} visible={isExporting}>
        <Loading text="处理中"></Loading>
      </Modal>
      <Modal animationType="fade" transparent={true} visible={isReplying}>
        <Loading text="发送中"></Loading>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
    // alignItems: "center",
    // justifyContent: "center",
    // backgroundColor: "#eee",
  },
  dropdownView: {
    flexDirection: "row",
    justifyContent: "center",
    marginBottom: 0,
    flex: 1,
  },
  headView: {
    padding: 10,
    margin: 5,
    marginLeft: 0,
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
    // backgroundColor: "#8ABAFF",
    flexDirection: "row",
  },
  optionBtn: {
    height: 40,
    width: 250,
    marginTop: 15,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#41C3EE",
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.5, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
  },
  ModalBackground: {
    backgroundColor: "#727272",
    opacity: 0.3,
    zIndex: 0,
    position: "absolute",
    width: "100%",
    height: "100%",
  },
  ModalStyle: {
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    backgroundColor: "#ffffff",
    zIndex: 1,
    position: "relative",
  },
  ModalTop: {
    flex: 1,
  },
  modalOption: {
    // backgroundColor: "yellow",
    width: "100%",
    padding: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: "#e6e6e6",
  },
  inputBox: {
    height: 40,
    // marginTop: 6,
    borderColor: "#ddd",
    borderWidth: 1,
    // height: 100,
    borderRadius: 3,
    // padding: 10,
    // paddingTop: 10,
    // paddingBottom: 10,
    marginLeft: 5,
    marginRight: 5,
    width: "76%",
  },
  replyBtn: {
    margin: 1,
    width: "20%",
    backgroundColor: "#41C3EE",
    borderRadius: 3,
    alignItems: "center",
    justifyContent: "center",
  },
  stateView0: {
    backgroundColor: "#86b8ff",
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 1,
    marginRight: 10,
    borderRadius: 2,
  },
  stateView1: {
    backgroundColor: "#9AEE91",
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 1,
    marginRight: 10,
    borderRadius: 2,
  },
  stateView2: {
    backgroundColor: "#F47C68",
    paddingLeft: 5,
    paddingRight: 5,
    paddingTop: 1,
    borderRadius: 2,
  },
  submitBtn: {
    // flex: 1,
    width: "35%",
    marginBottom: 10,
    marginLeft: 15,
    marginRight: 20,
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
  },
  backBtn: {
    width: "21%",
    marginBottom: 10,
    marginLeft: 15,
    borderWidth: 1,
    borderColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
    // width: 100,
  },
  selectView: {
    width: 14,
    height: 14,
    borderRadius: 7,
    borderWidth: 1,
    borderColor: "#ccc",
    marginTop: 4,
  },
  selectedView: {
    width: 14,
    height: 14,
    borderRadius: 7,
    borderWidth: 1,
    borderColor: "#eee",
    backgroundColor: "#41C3EE",
    marginTop: 4,
  },
  alterView: {
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  tag: {
    marginTop: 6,
    marginRight: 7,
    paddingLeft: 5,
    padding: 3,
    paddingRight: 5,
    borderRadius: 6,
  },
});

export default Opinions;
